/*
 ContributionViewController.m
 LegislatorLookup
 
 The class controls the Contribution View.
 
 Copyright (c) 2009 Nabil Ahmad
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 1. Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the 
 documentation and/or other materials provided with the distribution. 
 
 3. The name of the author may not be used to endorse or promote products
 derived from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */	

#import "ContributorViewController.h"
#import "WebServiceController.h"

#define LABEL_TAG 1
#define VALUE_TAG 2
#define FIRST_CELL_IDENTIFIER @"FIRST_CELL"

@implementation ContributorViewController

// custom init with candidate id
- (id) initWithCandidateId:(NSString *)candId {
	[super initWithStyle:UITableViewStyleGrouped];
	candidateId = candId;
	return self;
}

- (void)loadView {
	[super loadView];
	self.title = @"Top Contributors";
	isDataLoaded = NO;
}

// load data and rerender view after view is loaded
- (void)viewDidAppear:(BOOL)animated
{
	// load data
	contributionData = [[WebServiceController getCandidateTopContributions:candidateId] retain];
	isDataLoaded = YES;
	// make data is being returned properly
	if (contributionData == nil)
		dataError = YES;
	else
		dataError = NO;
	
	[self createTableHeaderAndFooter];	
	[self.tableView reloadData];
}

// This method loads the header and footer for the table
- (void) createTableHeaderAndFooter 
{
	// Header title
	CGRect titleRect = CGRectMake(0, 0, 320, 70);
    UILabel *tableTitle = [[UILabel alloc] initWithFrame:titleRect];
	tableTitle.numberOfLines = 0;
    tableTitle.textColor = [UIColor grayColor];
    tableTitle.backgroundColor = [UIColor clearColor];
    tableTitle.opaque = YES;
    tableTitle.font = [UIFont systemFontOfSize:12];
	tableTitle.textAlignment = UITextAlignmentCenter;
    self.tableView.tableHeaderView = tableTitle;
    [tableTitle release];
	
	// don't show the footer if there's a data issue
	// instead load error message into header label
	if (!dataError) {
		// Footer
		CGRect footerRect = CGRectMake(0, 0, 320, 30);
		UILabel *footerText = [[UILabel alloc] initWithFrame:footerRect];
		footerText.textColor = [UIColor grayColor];
		footerText.backgroundColor = [UIColor clearColor];
		footerText.opaque = YES;
		footerText.numberOfLines = 0;
		footerText.font = [UIFont systemFontOfSize:12];
		footerText.text = [NSString stringWithFormat:@"Content provided by %@",[[contributionData objectForKey:@"@attributes"] objectForKey:@"origin"]];
		footerText.textAlignment = UITextAlignmentCenter;
		self.tableView.tableFooterView = footerText;
		[footerText release];	
		
		// Set Header Title
		tableTitle.text = [NSString stringWithFormat:@"Note: %@",[[contributionData objectForKey:@"@attributes"] objectForKey:@"notice"]];
	} else {
		tableTitle.text = @"Either this information is not available for this candidate or there has been an error accessing the data";
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; 
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
		return 1;
}

// return number of contributors
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (!dataError && isDataLoaded)
		return [[contributionData objectForKey:@"contributor"] count];
	else
		return 0;
}


// return 2 column cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FIRST_CELL_IDENTIFIER];
	UILabel *label, *value;
	
	if (cell == nil) {
		
		CGRect frame = CGRectMake(0, 0, 300, 44);	
		cell = [[[UITableViewCell alloc] initWithFrame:frame reuseIdentifier:FIRST_CELL_IDENTIFIER] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		label = [[[UILabel alloc] initWithFrame:CGRectMake(5.0, 12.0, 200.0, 25.0)] autorelease];
		label.tag = LABEL_TAG;
		label.font = [UIFont boldSystemFontOfSize:12.0];
		label.textAlignment = UITextAlignmentLeft;
		label.textColor = [UIColor grayColor];
		label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
		[cell.contentView addSubview:label];
		
		value = [[[UILabel alloc] initWithFrame:CGRectMake(200, 12.0, 95.0, 25.0)] autorelease];
		value.tag = VALUE_TAG;
		value.font = [UIFont boldSystemFontOfSize:12.0];
		value.textColor = [UIColor blackColor];
		value.textAlignment = UITextAlignmentRight;
		value.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		[cell.contentView addSubview:value];
	} else {
		
		label = (UILabel *)[cell.contentView viewWithTag:LABEL_TAG];	
		value = (UILabel *)[cell.contentView viewWithTag:VALUE_TAG];
	}
	
	label.text = [[[[contributionData objectForKey:@"contributor"] objectAtIndex:indexPath.row] objectForKey:@"@attributes"] objectForKey:@"org_name"];

	// format amount
	NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
	[numberFormatter setPositiveFormat:@"$#,##0"];
	[numberFormatter setNegativeFormat:@"$#,##0"];
	
	int contribAmount = [[[[[contributionData objectForKey:@"contributor"] objectAtIndex:indexPath.row] objectForKey:@"@attributes"] objectForKey:@"total"] intValue];
	value.text = [numberFormatter stringFromNumber:[NSNumber numberWithInt:contribAmount]];
	
	return cell;
}

- (void)dealloc {
    [super dealloc];
	[contributionData dealloc];
}


@end

